package com.longyiqun.apitest.nouse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.LinkedHashMap;

/**
 * Created by testypp on 2017/5/22.
 */
public class SignatureUtil_OLD {
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String X_REQUESTED_WITH = "X-Requested-With";
    private static final String X_VNUM = "X-Vnum";
    private static final String X_CHANNEL = "X-Channel";
    private static final String X_DEVICE = "X-Device";
    private static final String X_UDID = "X-Udid";
    private static final String X_CLIENT_TIME = "X-Client-Time";
    private static final String X_PUB_KEY = "X-Pub-Key";
    private static final String X_SIGNATURE = "X-Signature";
    private static final String X_AUTHORIZATION = "X-Authorization";

    private static final String MAGIC_SEPARATOR = "￥";
    private static final String MAGIC_KEY = "qazxrtg98765bnhyujmiklop102345swecvf";

    public static LinkedHashMap<String, String> header(String timespan, String key, String sign) {
        LinkedHashMap<String, String> headerMap = new LinkedHashMap<>();
        headerMap.put(CONTENT_TYPE, "application/json; charset=UTF-8");
        headerMap.put(X_REQUESTED_WITH, "XMLHttpRequest");
        headerMap.put(X_VNUM, "59");
        headerMap.put(X_CHANNEL, "wywk");
        headerMap.put(X_DEVICE, "android");
        headerMap.put(X_UDID, "865291027696342e534f561848a8140");
        headerMap.put(X_CLIENT_TIME, timespan);
        headerMap.put(X_PUB_KEY, key);
        headerMap.put(X_SIGNATURE, sign);
        headerMap.put(X_AUTHORIZATION, headerSignature(headerMap));

        return headerMap;
    }

    //返回值就是keyt,参数data请求体数据
    public static String bodySignature(String data) {
        long curTime = System.currentTimeMillis();
        String vNum = "59";
        String uuid = "";

        StringBuilder srcBuilder = new StringBuilder();
        boolean isEvenNum = curTime % 2 == 0;
        if (isEvenNum) {
            srcBuilder.append(MAGIC_KEY)
                    .append(MAGIC_SEPARATOR);
        }

        srcBuilder.append(isEvenNum ? vNum : uuid)
                .append(MAGIC_SEPARATOR)
                .append(data)
                .append(MAGIC_SEPARATOR)
                .append(isEvenNum ? uuid : vNum);

        if (!isEvenNum) {
            srcBuilder.append(MAGIC_SEPARATOR)
                    .append(MAGIC_KEY);
        }

        return MD5Utils_OLD.getMD5(srcBuilder.toString());
    }

    public static String headerSignature(LinkedHashMap<String, String> headerMap) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String headerStr = gson.toJson(headerMap);

        return MD5Utils_OLD.getMD5(headerStr);
    }
}
